import React from 'react';
import Head from 'next/head'
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import { Button, Snackbar, SnackbarContent, TextField, Paper } from '@material-ui/core';
import { Error } from '@material-ui/icons';
import Router from 'next/router'
import { red } from '@material-ui/core/colors';
import styled from 'styled-components';
import validator from 'validator';
import swal from 'sweetalert2';
import axios from 'axios';
import withRoot from '../components/withRoot';


const AuthWrapper = styled.div`
margin: 0 auto;
max-width: 600px;
padding-top: 60px;
width: 90%;
@media (min-width: 768px) {
    margin: -160px 0 0 -300px;
position: absolute;
left: 50%;
top: 40%;
}
@media (max-width: 767px) {
    padding-bottom: 30px;
}
position: relative;
z-index:100;
`;
const Body = styled.div`
color: #fff;
border: 0;
height: 100%;
margin: 0;
// width:100%;
display: flex!important;
// padding: 120px 0;
position: relative;
min-height: 100vh;
align-items: center;
background-size: cover;
background-position: center center;
background-image: url('/static/img/login.jpeg');
&:before{
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: block;
    content: "";
    z-index: 2;
    position: absolute;
    background-color: rgba(0, 0, 0, 0.65);
}

`;
const AuthBoxInner = styled.div`
display: -webkit-flex; /* Safari */
display: flex;

@media (max-width: 767px) {
    flex-wrap: wrap;
}
align-items: center; 
margin-left: -10px;
margin-right: -10px;
`;
const AuthBoxCol = styled.div`
padding-left: 10px;
padding-right: 10px;
width: 100%;
@media (min-width: 768px) {
    width: 50%;
}
`;
const LeftImg = styled.img`
 
width: 100%;
 
`;

const AuthBoxDrand = styled.div`
@media (min-width: 768px) {
    border-right: 1px solid #eee;
    min-height: 185px;
    line-height: 185px;
    padding-right: 30px;
    padding-top:40px;
}
@media (max-width: 767px) {
    border-bottom: 1px solid #eee;
    margin-bottom: 30px;
    padding-bottom: 30px;
   
}
`;
const SnackbarText = styled.span`
display: flex;
 align-items: center; 

`;
const ItemTextField = styled(TextField)`
&&{
    // margin: 27px 0 0 0;
    position: relative;
    padding-bottom: 10px;
    width:100%;
    font-size:16px;
}
`;
const SnackbarDetails = styled(SnackbarContent)`
&&{
    background-color : ${props => props.colors};
}
`;
const SubmitButton = styled(Button)`
&&{
    margin:10px auto;
    display: block;
    width: 100%;
}
`;
const styles = theme => ({
    root: {
        width: '100%',
        padding: '30px'
    },
    row: {
        display: 'flex',
        justifyContent: 'space-around',
        padding: '10px 10px 0 10px'
    },

});

class MenuAppBar extends React.Component {
    static async getInitialProps({ req, res, query }) {
        const isClient = !req
        if (isClient) {

            const { data } = await axios.get("/a/login", {
                withCredentials: true
            });
            if (data.user) {
                Router.push({
                    pathname: '/index'
                });
            }
            return {};

        } else {

            return {};
        }


    }
    constructor(props) {
        super(props);
        this.state = {
            phone: '',
            password: '',
            callback_url: '/',
            vertical: 'top', horizontal: 'center',
            snackbar_open: false,
            errMessage: '',
        };

        // This binding is necessary to make `this` work in the callback

        this.handleSubmit = this.handleSubmit.bind(this);

    }
    componentDidMount() {
        document.addEventListener('keydown', this.onKeyEnter);
    }

    componentWillUnmount() {
        document.removeEventListener('keydown', this.onKeyEnter);
    }

    onKeyEnter = (ev) => {

        if (ev.keyCode == 13) {
            this.handleSubmit();
        }

    }
    handleClose = () => {
        this.setState({ snackbar_open: false });
    };
    handleChange = (ev, change_index, value) => {

        let fields = { none: ev.target.value }
        switch (change_index) {
            case 0:
                fields = { phone: ev.target.value }
                break;
            case 1:

                fields = { password: ev.target.value }
                break;

        }
        this.setState(fields);

    }
    // 提交信息
    handleSubmit() {

        let { phone, password, callback_url } = this.state;

        phone = validator.trim(phone);
        if (phone == '') {
            return this.setState({
                errMessage: '请输入手机号',
                snackbar_open: true
            })
        }
        if (!validator.isMobilePhone(phone, 'zh-CN')) {

            return this.setState({
                errMessage: '请输入正确的手机号',
                snackbar_open: true
            })
        }
        password = validator.trim(password);
        if (password == '') {
            return this.setState({
                errMessage: '请输入密码',
                snackbar_open: true
            })
        }
        let formData = new FormData();

        // 请求参数 ('key',value)
        formData.append('phone', phone);
        formData.append('password', password);

        formData.append('callback_url', callback_url);
        formData.append('type', 'login');


        axios({
            url: "/local/local_user",
            method: 'post',
            data: formData,
            withCredentials: true,
        })
            .then(response => {
                // console.log(response)
                return response.data;
            })
            .then(json => {
                // console.log(json)
                if (json.err == 0) {
                    document.removeEventListener('keydown', this.onKeyEnter);
                    swal({
                        title: "登录成功",
                        text: "2秒后自动跳转",
                        timer: 2000,
                        showConfirmButton: false,
                        type: "success",
                    });
                    setTimeout(() => {
                        Router.push({
                            pathname: '/index'
                        });
                    }, 2000)

                } else if (json.info == 'err_phone') {
                    swal(
                        '登录失败',
                        `此账号不存在!`,
                        'error',
                    );
                } else if (json.info == 'err_password') {
                    swal(
                        '登录失败',
                        `密码错误,请重新输入!`,
                        'error',
                    );
                }
                return json;
            }).catch(err => {
                console.log(err)
            })
    }

    render() {
        const { classes } = this.props;
        const { phone, password, vertical, horizontal, snackbar_open, errMessage } = this.state;

        return (
            <div >
                <Head>

                    <title>登录</title>

                </Head>
                <Snackbar

                    anchorOrigin={{ vertical, horizontal }}
                    open={snackbar_open}

                    autoHideDuration={3000}
                    onClose={this.handleClose}

                >
                    <SnackbarDetails
                        colors={red[600]}
                        aria-describedby="client-snackbar"
                        message={
                            <SnackbarText id="client-snackbar"  >
                                <Error className={classes.success_icon} />
                                {errMessage}
                            </SnackbarText>
                        }

                    />
                </Snackbar>
                <Body>
                    <AuthWrapper >

                        <Paper className={classes.root}>
                            <AuthBoxInner>
                                <AuthBoxCol>
                                    <AuthBoxDrand><LeftImg src='/static/img/login_logo.png' /></AuthBoxDrand>
                                </AuthBoxCol>
                                <AuthBoxCol>


                                    <ItemTextField
                                        id="standard-name"
                                        autoComplete="off"
                                        label="手机号"
                                        type="text"
                                        className={classes.cssUnderline}
                                        value={phone}
                                        margin="normal"
                                        onChange={(ev, change_index, value) => this.handleChange(ev, 0, value)}
                                    />

                                    <ItemTextField
                                        id="standard-password"
                                        autoComplete="off"
                                        label="密码"
                                        className={classes.cssUnderline}
                                        value={password}
                                        type="password"
                                        margin="normal"

                                        onChange={(ev, change_index, value) => this.handleChange(ev, 1, value)}
                                    />


                                    <SubmitButton variant="contained" color="primary" onClick={this.handleSubmit}>登 录</SubmitButton>

                                </AuthBoxCol>
                            </AuthBoxInner>

                        </Paper>
                    </AuthWrapper>
                </Body>

            </div>
        );
    }
}

MenuAppBar.propTypes = {
    classes: PropTypes.object.isRequired,
    theme: PropTypes.object.isRequired,
};

export default withRoot(withStyles(styles, { withTheme: true })(MenuAppBar));
